<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Brand;
use App\Models\Template;

class FormatTemplate extends Command {
    
    protected $signature = 'ft';
    protected $description = 'FormatTemplate';
    
    public function __construct() {
        parent::__construct ();
    }
    
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function handle() {
        $this->error('开始格式化模板信息');
        $brands = Brand::select('name', 'oldprice')->get();
        foreach ($brands as $brand) {
            $tcs = Template::where('name', 'like', '%'.$brand->name.'%')->count();
            if($tcs > 0) {
                $templates = Template::where('name', 'like', '%'.$brand->name.'%')->select('name', 'content')->get();
                $this->formatTemplate($templates, $brand);
                unset($templates);
            }else {
                $this->info('没有要格式化的模板！ '.$brand->name);
            }
            unset($brand);
        }
    }
    
    public function formatTemplate($templates, $brand) {
        $count = count($templates);
        $i = 1;
        foreach ($templates as $template) {
            $name = $template->name;
            $template->name = $this->formatContent($template->name, $brand);
            $template->content = $this->formatContent($template->content, $brand);
            $template->save();
            $this->info($brand->name.' '.$i. '/'. $count.' '.$name.'==>'.$template->name);
            $i++;
            unset($name);
            unset($template);
        }
        unset($brand);
    }
    
    public function formatContent($content, $brand) {
        $format = str_replace($brand->name, "{name}", $content);
        $format = str_replace($brand->oldprice, "{price}", $format);
        return $format;
    }
}
